const express = require("express");
const mongoose = require("mongoose");
//请求的中间件.解析post
const bodyParser = require("body-parser");
// 生成token
const passport = require("passport");
const app = express();

// 跨域
app.all("*", function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "*");
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By", " 3.2.1");
  res.header("Access-Control-Expose-Headers", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "x-requested-with,Authorization,content-type"
  );
  next();
});

/**
 * @name bodyParser
 * 请求的中间件.解析post
 */

// parse application/x-www-form-urlencoded
app.use(
  bodyParser.urlencoded({
    extended: false,
  })
);
// parse application/json
app.use(bodyParser.json());

const users = require("./routers/api/user");
const types = require("./routers/api/type");
const bikes = require("./routers/api/bike");
const moneys = require("./routers/api/money");
const rents = require("./routers/api/rents");
app.use("/static", express.static("static"));
app.use("/bicycle/users", users);
app.use("/bicycle/types", types);
app.use("/bicycle/bikes", bikes);
app.use("/bicycle/moneys", moneys);
app.use("/bicycle/rents", rents);

var session = require("express-session");
app.use(
  session({
    secret: "keyboard cat",
    resave: false,
    saveUninitialized: true,
    cookie: {
      secure: false,
    },
  })
);

/**
 * 数据库的连接
 */
const User = require("./models/User");

const md5 = require("md5");
const options = { useNewUrlParser: true, useUnifiedTopology: true }
mongoose
  .connect(`mongodb://admin:15383645663.rH@127.0.0.1:18001/bicycle?authSource=admin`,
    options)
  .then(() => {
    User.find({ username: "admin" }).then((res) => {
      if (res.length === 0) {
        const newUser = new User({
          username: "admin",
          password: md5("123456"),
          name: "admin",
          grade: 999,
        });
        newUser
          .save()
          .then((user) => {
            console.log("admin添加成功");
          })
          .catch((err) => console.log(err));
      } else {
        console.log("数据库启动成功");
      }
    });
  })
  .catch((err) => {
    console.log(err);
    console.log("失败");
  });

// 使用中间件。进行token的验证
app.use(passport.initialize());
require("./config/passport")(passport);

/**
 * 设置端口
 */
const port = process.env.PORT || 8090;
app.listen(port, () => {
  console.log("服务器启动成功", port);
});
